package cn.edu.sdjzu.xg.kcsj.service;

import cn.edu.sdjzu.xg.kcsj.dao.CourseArrangementDao;
import cn.edu.sdjzu.xg.kcsj.domain.CourseArrangement;
import util.JdbcHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public class CourseArrangementService {
    private static CourseArrangementService courseArrangementService = null;
    private static CourseArrangementDao courseArrangementDao = CourseArrangementDao.getInstance();

    private CourseArrangementService() {
    }

    public static CourseArrangementService getInstance() {
        if (courseArrangementService == null) {
            courseArrangementService = new CourseArrangementService();
        }
        return courseArrangementService;
    }


    public Collection<CourseArrangement> findAll () throws SQLException {
        Connection connection = JdbcHelper.getConn ();
        Collection<CourseArrangement> courseArrangements = courseArrangementDao.findAll(connection,null,null);
        JdbcHelper.close (connection);
        return courseArrangements;
    }

    public CourseArrangement find (int id) throws SQLException {
        Connection connection = JdbcHelper.getConn ();
        CourseArrangement courseArrangement = courseArrangementDao.find(id,connection);
        JdbcHelper.close (connection);
        return courseArrangement;
    }

    public Boolean add (CourseArrangement courseArrangement) throws SQLException {
        Connection connection = JdbcHelper.getConn ();
        boolean add = CourseArrangementDao.getInstance ().add(courseArrangement,connection);
        JdbcHelper.close (connection);
        return add;
    }

    public boolean delete (int id) throws SQLException {
        Connection connection = JdbcHelper.getConn ();
        boolean delete = CourseArrangementDao.getInstance ().delete(id,connection);
        return delete;
    }

    public boolean deletes(List<CourseArrangement> listToDelete) throws SQLException{
        Connection connection = JdbcHelper.getConn();
        //���Զ��ύ��Ϊfalse,��ʼ����
        connection.setAutoCommit(false);
        Boolean deleted =false;
        try {
            for(CourseArrangement e:listToDelete) {
                int id= e.getId();
                //ɾ���û�
                deleted = CourseArrangementDao.getInstance ().delete(id,connection);
            }
            //�ύ����
            connection.commit();
        }catch (Exception e){
            //�ع�
            connection.rollback();
        }finally {
            //���Զ��ύ��Ϊtrue����������
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }
        return deleted ;
    }

    public boolean update (CourseArrangement courseArrangement) throws SQLException {
        Connection connection = JdbcHelper.getConn ();
        boolean update = CourseArrangementDao.getInstance ().update(courseArrangement,connection);
        return update;
    }
}
